﻿using Microsoft.EntityFrameworkCore;
using MT.Common;
using MT.Common.EfExtenstion;
using MT.DAL.Infrastructure;
using MT.Models.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MT.DAL.Dto.UserCenter
{
    public class UserDto : RepositoryBase<User>
    {
        public UserDto(AppDbContext dbContext) : base(dbContext)
        {
        }

     
        public async Task<List<User>> UpdateRestAsync(List<User> list)
        {
           await  UpdateRestValueAsync(list.AsQueryable(), x => x.UpdateTime == DateTime.Now);
            return list;
        }
        public async Task<PageModel<User>> GetPageAsync(int pageIndex, int pageSize, string name, int? institutionId)
        {

            //var filter = PredicateExtensionses.True< User>().And(f => f.Delete == false);
            var result = DataContext.User.AsQueryable();
            if (!string.IsNullOrWhiteSpace(name))
            {
                result = result.Where(s => s.Name.Contains(name));
            }
            if (institutionId != null)
            {

                result = result.Join(DataContext.UserInstitution.Where(s => s.InstitutionId == institutionId.Value), u => u.Id, i => i.UserId, (u, i) => u);
            }
            result = result.Where(f => f.Delete == false);
            result = result.OrderByDescending(x => x.CreateTime);
            var count = result.Count();
            var list =await  result.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            return new PageModel<User>(pageIndex, pageSize, list, count);
        }

        public async Task<PageModel<User>> GetPageAsync(int pageIndex, int pageSize, string keyword, int? storeId = null, string businessRoleDic = null)
        {
            var filter = PredicateExtensionses.True<User>().And(f => f.Delete == false);
            var result = DataContext.User.AsQueryable();
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                result = result.Where(s => s.Name.Contains(keyword) || s.PhoneNumber.Contains(keyword));
            }
            if (storeId != null)
            {

            }
            if (!string.IsNullOrWhiteSpace(businessRoleDic))
            {

                result = result.Join(DataContext.UserBusinessRole.Where(s => s.BusinessRoleDic == businessRoleDic), u => u.Id, s => s.UserId, (u, i) => u);
            }
            result.Where(f => f.Delete == false);
            result = result.OrderByDescending(x => x.CreateTime);
            var count = await result.CountAsync();
            var list = await result.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            return new PageModel<User>(pageIndex, pageSize, list, count);
        }
    }
}
